package com.dempsey.miaosha.controller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dempsey.api.RemoteGoodService;
import com.dempsey.api.domain.Order;
import com.dempsey.common.core.domain.AjaxResult;
import com.dempsey.common.core.domain.R;
import com.dempsey.common.redis.service.RedisService;
import com.dempsey.common.security.annotation.RequiresRoles;
import com.dempsey.common.security.utils.SecurityUtils;
import com.dempsey.miaosha.dao.Acticity;
import com.dempsey.miaosha.service.ActicityService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

/**
 * The type Miaosha controller.
 *
 * @author Dempsey  Date 2022/5/23 Description
 */
@RestController
@RequestMapping("/seckill")
public class MiaoshaController {

    private final static Log log = LogFactory.get();

    @Autowired
    private ActicityService acticityService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RemoteGoodService remoteGoodService;

    @Autowired
    private RedisService redisService;


    @PostMapping("/getActivityById")
    public AjaxResult getActivityById(@RequestParam int acticityId) {
        log.info("请求参数: {}", acticityId);

        Acticity acticity = acticityService.getById(acticityId);
        return AjaxResult.success(acticity);
    }

    @PostMapping("/getActivityByGoodId")
    public AjaxResult getActivityByGoodId(@RequestParam int goodId) {
        log.info("请求参数: {}", goodId);

        QueryWrapper<Acticity> qw = new QueryWrapper<>();
        qw.eq("good_id", goodId);
        Acticity acticity = acticityService.getOne(qw);

        return AjaxResult.success(acticity);
    }

    @PostMapping("/getActivityByUserId")
    public AjaxResult getActivityByUserId(@RequestParam int userId) {
        log.info("请求参数: {}", userId);

        QueryWrapper<Acticity> qw = new QueryWrapper<>();
        qw.eq("create_user", userId);
        qw.orderByAsc("start_time");
        List<Acticity> acticityList = acticityService.list(qw);

        return AjaxResult.success(acticityList);
    }

    @RequiresRoles({"merchant", "admin"})
    @PostMapping("/createActivity")
    public AjaxResult createActivity(@RequestBody Acticity acticity) {
        log.info("请求参数: {}", acticity);

        Timer timer = new Timer(true);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                // 先刷库存缓存
                remoteGoodService.getStock(acticity.getGoodId());
                // 再加随机字符串做校验
                String uuid = IdUtil.simpleUUID();
                long between = DateUtil.between(acticity.getStartTime(), acticity.getEndTime(), DateUnit.SECOND);
                redisService.setCacheObject("seckill-acticity:" + acticity.getGoodId(), uuid, between, TimeUnit.SECONDS);
                log.info("执行了定时任务，活动商品id：{}，活动随机字符串：{}", acticity.getGoodId(), uuid);
            }
        }, acticity.getStartTime());

        acticity.setCreateUer(SecurityUtils.getLoginUser().getUser().getUserId());
        acticityService.save(acticity);
        return AjaxResult.success();
    }

    @PostMapping("/updateActivity")
    public AjaxResult updateActivity(@RequestBody Acticity acticity) {
        log.info("请求参数: {}", acticity);

        // 按理说要删掉之前的timer（命名），重新创建一个，这边不考虑了

        acticity.setUpdateUser(SecurityUtils.getLoginUser().getUser().getUserId());
        acticityService.updateById(acticity);
        return AjaxResult.success();
    }

    @PostMapping("/createSeckillOrder")
    public AjaxResult createSeckillOrder(@RequestBody Order order) {
        log.info("请求参数: {}", order);
        // 1、根据商品id查询库存是否充足
        R<Integer> result = remoteGoodService.getStock(order.getGoodId());
        if (result.getData() > 0) {
            // 2、通过mq实现消息分发
            // 参数1: 交换机  参数2: 路由key/queue队列名 参数3: 消息内容
            String exchangeName = "fanout_order_exchange";
            String routingKey = "";
            String orderString = JSON.toJSONString(order);
            rabbitTemplate.convertAndSend(exchangeName, routingKey, orderString);
            log.info("向消息队列中发送数据: {}", orderString);
            return AjaxResult.success();
        }
        return AjaxResult.error("库存不足");
    }


}
